package afcepf.atod18.frameworkMVC2.servlet;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class FilesSearch {
    private static final Logger logger = Logger.getLogger(FilesSearch.class);

    private String fileNameToSearch;
    private List<String> result = new ArrayList<String>();

    public String getFileNameToSearch() {
        return fileNameToSearch;
    }

    public void setFileNameToSearch(String fileNameToSearch) {
        this.fileNameToSearch = fileNameToSearch;
    }

    public List<String> getResult() {
        return result;
    }

    public void searchDirectory(File directory, String fileNameToSearch) {

        setFileNameToSearch(fileNameToSearch);

        if (directory.isDirectory()) {
            search(directory);
        } else {
            logger.info("FilesSearch: " + directory.getAbsoluteFile()
                    + " is not a directory!");
        }
    }

    private void search(File file) {

        if (file.isDirectory()) {
            logger.info("FilesSearch: Scanning directory "
                    + file.getAbsoluteFile());

            // do you have permission to read this directory?
            if (file.canRead()) {
                for (File temp : file.listFiles()) {
                    if (temp.isDirectory()) {
                        search(temp);
                    } else {
                        if ( temp.getName().toLowerCase().endsWith( getFileNameToSearch())) {
                            result.add(temp.getAbsoluteFile().toString());
                        }
                    }
                }
            } else {
                logger.info("FilesSearch: " + file.getAbsoluteFile()
                        + "Permission Denied");
            }
        }
    }
}
